package com.tsing.cli.common.config;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * WebSocket管理类
 *
 * @author TheTsing
 */
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{id}")
public class WebSocketManager {

    private String id = "";

    private Session session;

    private static int onlineCount = 0;

    private static final CopyOnWriteArraySet<WebSocketManager> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        log.info("【 客户端：{} 连接成功，当前在线人数为：{} 】", id, getOnlineCount());
        this.id = id;
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        log.info("【 有一个连接关闭，当前在线人数为：{} 】", getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("【 收到来自客户端：{} 的信息：{} 】", id, message);
    }

    @OnError
    public void onError(Session session, Throwable e) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        try (stringWriter; printWriter) {
            e.printStackTrace(printWriter);
            log.error(stringWriter.toString());
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message, @PathParam("id") String id) {
        log.info("【 推送消息到客户端：{}，内容：{} 】", id, message);
        for (WebSocketManager item : webSocketSet) {
            try {
                if (Objects.isNull(id)) {
                    item.sendMessage(message);
                } else if (item.id.equals(id)) {
                    item.sendMessage(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketManager.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketManager.onlineCount--;
    }

}
